# -*- coding:utf-8 -*-
from flask import Flask, abort
from flask_restful import reqparse, abort, Api, Resource
from flask_restful import fields, marshal
from resources import weather_info
import lstm_predict
import tensorflow as tf
from flask_cors import *
from keras.models import load_model
import keras

app = Flask(__name__)
CORS(app, supports_credentials=True)
api = Api(app)

# we need to redefine our metric function in order
# to use it when loading the model
def auc(y_true, y_pred):
    auc = tf.metrics.auc(y_true, y_pred)[1]
    keras.backend.get_session().run(tf.local_variables_initializer())
    return auc


# load the model, and pass in the custom metric function
# global graph
# graph = tf.get_default_graph()
# model = load_model("games.h5", custom_objects={"auc": auc})

lstm = lstm_predict.LSTMNER()

tasks = [
    {
        "todo_id": 1,
        "title": u"Buy groceries",
        "description": u"Milk, Cheese, Pizza, Fruit, Tylenol",
        "done": False,
    },
    {
        "todo_id": 2,
        "title": u"Learn Python",
        "description": u"Need to find a good Python tutorial on the web",
        "done": False,
    },
]

task_fields = {
    "title": fields.String,
    "description": fields.String,
    "done": fields.Boolean,
    "uri": fields.Url("task"),
}


def abort_if_todo_doesnt_exist(todo_id):
    task = filter(lambda t: t["todo_id"] == todo_id, tasks)
    if len(task) == 0:
        abort(404, message="Todo {todo_id} doesn't exist".format(todo_id=todo_id))
    else:
        return task[0]


class Task(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument("title", type=str, location="json")
        self.reqparse.add_argument("description", type=str, location="json")
        self.reqparse.add_argument("done", type=bool, location="json")
        super(Task, self).__init__()

    def get(self, todo_id):
        task = abort_if_todo_doesnt_exist(todo_id)
        return marshal(task, task_fields), 201

    def delete(self, todo_id):
        task = abort_if_todo_doesnt_exist(todo_id)
        tasks.remove(task)
        # del task
        return marshal(tasks, task_fields), 204

    def put(self, todo_id):
        new_task = abort_if_todo_doesnt_exist(todo_id)
        args = self.reqparse.parse_args()
        print(args)
        for k, v in args.iteritems():
            if v is not None:
                new_task[k] = v
        print(new_task)
        return marshal(new_task, task_fields), 201


class TaskList(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument(
            "todo_id",
            type=int,
            required=True,
            help="No todo id provided",
            location="json",
        )
        self.reqparse.add_argument(
            "title",
            type=str,
            required=True,
            help="No task title provided",
            location=["json"],
        )
        self.reqparse.add_argument("description", type=str, default="", location="json")
        self.reqparse.add_argument("done", type=bool, default=False, location="json")
        super(TaskList, self).__init__()

    def get(self):
        return marshal(tasks, task_fields), 201

    def post(self):
        args = self.reqparse.parse_args()
        new_task = {}
        for k, v in args.iteritems():
            if v is not None:
                new_task[k] = v
        tasks.append(new_task)
        return marshal(new_task, task_fields), 202


class Index(Resource):
    def get(self):
        weinfo = weather_info.getWeatherInfo("beijing")
        return {"result": weinfo}, 200


class WeatherInfo(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument("city", required=True, help="No city provided")

    def post(self):
        args = self.reqparse.parse_args()
        print(args)
        weinfo = weather_info.getWeatherInfo(args["city"])
        return {"result": weinfo}, 200


class ICDInfo(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument("text", required=True, help="No text provided")
        # self.lstm = lstm_predict.LSTMNER()

    # @cross_origin()
    def post(self):
        # load the model, and pass in the custom metric function
        # global graph
        # graph = tf.get_default_graph()

        args = self.reqparse.parse_args()
        print(args)

        # with graph.as_default():
        # icd_result = lstm_predict.LSTMNER().get_icd11_codes(args["text"])
        icd_result = lstm.get_icd11_codes(args["text"])
        return {"result": icd_result}, 200


api.add_resource(TaskList, "/todo/api/v1.0/tasks", endpoint="tasks")
api.add_resource(Task, "/todo/api/v1.0/tasks/<int:todo_id>", endpoint="task")
api.add_resource(Index, "/", endpoint="index")
api.add_resource(WeatherInfo, "/weather", endpoint="weather")
api.add_resource(ICDInfo, "/icdinfo", endpoint="ICDInfo")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8889, debug=False)
    # app.run(port=8889, debug=False)
